import axios from 'axios'
import CryptoJS from 'crypto-js/crypto-js'
import FingerprintJS from '@fingerprintjs/fingerprintjs';

import env from '@/envconfig/index';
// 根据环境不同引入不同api地址

//获取设备唯一id
async function getDeviceId() {
  const fpPromise = FingerprintJS.load();
  const fp = await fpPromise
  const result = await fp.get()
  // This is the visitor identifier:
  const visitorId = result.visitorId
  if (!localStorage.getItem('deviceId')) {
    window.localStorage.setItem('deviceId', visitorId)
  }
}

function JsonToUrl(data) {
  var tempArr = [];
  for (var i in data) {
    var key = i;
    var value = data[i];
    tempArr.push(key + '=' + value);
  }
  var urlParamsStr = tempArr.join('&');
  return urlParamsStr;
}

function changeMethods(key) {
  switch (key) {
    case 'get':
      return 'GET'
    case 'post':
      return 'POST'
    case 'delete':
      return 'DELETE'
    default:
      return key
  }
}

function getSign(config) {
  let body = JSON.stringify(config.data) || JsonToUrl(config.params, config.isnftParams) || 'null',
    url = config.url,
    method = changeMethods(config.method),
    AppType = 6,
    LoginType = 2,
    DeviceId = window.localStorage.getItem('deviceId'),
    timestamp = Number(new Date().getTime()) - (window.diff ? Number(window.diff) : 0),
    str = body + url + method + DeviceId + timestamp,
    sign = CryptoJS.HmacSHA256(str, env.key), //process.env.key为密钥
    hashInBase64 = CryptoJS.enc.Base64.stringify(sign);
  config.headers['Authorization'] = localStorage.getItem('token') ? 'Bearer ' + localStorage.getItem('token') : ''
  config.headers['Login-Type'] = LoginType
  config.headers['Sign'] = hashInBase64
  config.headers['version'] = '1.1.8'
  config.headers['app-type'] = AppType
  config.headers['Device'] = 'web'
  config.headers['lang'] = navigator.language
  config.headers['Timestamp'] = timestamp
  config.headers['Device-ID'] = DeviceId
  config.headers['app-id'] = 2
  config.headers['app-lang'] = 'zh'
  config.headers['Content-Type'] = 'application/json;charset=utf-8'
  return hashInBase64
}

// create an axios instance
const service = axios.create({
  baseURL: window.config.baseApi, // url = base api url + request url
  withCredentials: true,
  timeout: 8000
})

let serverTimeCount = 0

// request拦截器 request interceptor
service.interceptors.request.use(
  config => {
    serverTimeCount++
    var Ajax = {
      get: function (url, fn) {
        // XMLHttpRequest对象用于在后台与服务器交换数据   
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.onreadystatechange = function () {
          // readyState == 4说明请求已完成
          if (xhr.readyState == 4) {
            if (xhr.status == 200 || xhr.status == 304) {
              fn.call(this, xhr.response);
            } else {
              fn.call(this, 'error')
            }
          }
        };
        xhr.send();
      }
    }

    if (serverTimeCount % 3 == 0) {
      Ajax.get(`${config.baseURL}api/v3/general/servertime`, (res) => {
        if (res.result == 1) {
          window.diff = new Date().getTime() - res.data
        }
      })
    }

    if (!window.localStorage.getItem('deviceId')) {
      getDeviceId().then(() => {
        getSign(config)
      })
    } else {
      getSign(config)
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    return Promise.resolve(res)
  },
  error => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

service.defaults.transformResponse = [
  data => {
    return jsonlint.parse(data)
  }
]

export default service